package com.geen.tuoke.base

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.geen.tuoke.network.api.apiService
import com.geen.tuoke.utils.SingleLiveEvent
import com.geen.tuoke.utils.ext.request
import com.geen.tuoke.utils.ext.toastShort
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.launch
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File


open class BaseViewModel() : ViewModel() {

    val commonUILiveData: CommonUILiveData by lazy { CommonUILiveData() }

    fun launchUI(block: suspend CoroutineScope.() -> Unit) =
        viewModelScope.launch { block() }

    @FlowPreview
    fun <T> launchFlow(block: suspend () -> T): Flow<T> =
        flow { emit(block()) }

    class CommonUILiveData : SingleLiveEvent<Any>() {
        val showDialog: SingleLiveEvent<String> by lazy { SingleLiveEvent<String>() }
        val dismissDialog: SingleLiveEvent<Boolean> by lazy { SingleLiveEvent<Boolean>() }
    }

    /***
     * 上传文件
     * @param filePath String
     */
    fun uploadFile(taskName: String, filePath: String, uploadCallBack: () -> Unit) {
        val file = File(filePath)
        if (!file.exists()) {
            return
        }
        val body: RequestBody =
            RequestBody.create(MediaType.parse("multipart/form-data"), file) //说明该文件为图片类型
        val part = MultipartBody.Part.createFormData("file", file.name, body)
        request({ apiService.uploadFile(taskName, part) }, {
            uploadCallBack()
        }, {
            toastShort(it.errorMsg)
        }, true)
    }

}